# -*- coding: utf-8 -*-
# diagnose.py
import sys
import os
import subprocess
import socket
import platform

def check_python():
    print("🐍 Python环境检查")
    print("-" * 30)
    print(f"Python版本: {sys.version}")
    print(f"Python路径: {sys.executable}")
    print(f"操作系统: {platform.system()} {platform.release()}")
    print()

def check_streamlit_installation():
    print("📦 Streamlit安装检查")
    print("-" * 30)
    try:
        result = subprocess.run([sys.executable, "-m", "pip", "show", "streamlit"], 
                              capture_output=True, text=True)
        if result.returncode == 0:
            print("✅ Streamlit已安装")
            print(result.stdout)
        else:
            print("❌ Streamlit未安装")
            print(result.stderr)
    except Exception as e:
        print(f"❌ 检查失败: {e}")
    print()

def check_port():
    print("🌐 端口检查")
    print("-" * 30)
    def is_port_open(port):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)
        result = sock.connect_ex(('localhost', port))
        sock.close()
        return result == 0
    
    ports_to_check = [8501, 8502, 8503, 8000, 3000]
    for port in ports_to_check:
        status = "占用" if is_port_open(port) else "可用"
        print(f"端口 {port}: {status}")
    print()

def check_streamlit_command():
    print("⚡ Streamlit命令检查")
    print("-" * 30)
    try:
        result = subprocess.run(["streamlit", "--version"], 
                              capture_output=True, text=True)
        if result.returncode == 0:
            print("✅ streamlit命令可用")
            print(result.stdout)
        else:
            print("❌ streamlit命令不可用")
            print(result.stderr)
    except FileNotFoundError:
        print("❌ 找不到streamlit命令")
        print("尝试使用: python -m streamlit --version")
        try:
            result = subprocess.run([sys.executable, "-m", "streamlit", "--version"], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                print("✅ python -m streamlit命令可用")
                print(result.stdout)
            else:
                print("❌ python -m streamlit命令也不可用")
        except Exception as e:
            print(f"❌ 都不可用: {e}")
    print()

def try_start_streamlit():
    print("🚀 尝试启动Streamlit")
    print("-" * 30)
    
    # 创建简单的测试文件
    test_content = """
import streamlit as st
st.write("测试页面")
st.success("如果你看到这个，Streamlit工作正常！")
"""
    
    with open("auto_test.py", "w", encoding="utf-8") as f:
        f.write(test_content)
    
    print("已创建 auto_test.py")
    print("请手动运行: streamlit run auto_test.py")
    print("或者: python -m streamlit run auto_test.py")
    

if __name__ == "__main__":
    print("🔍 Streamlit环境诊断工具")
    print("=" * 50)
    
    check_python()
    check_streamlit_installation()
    check_port()
    check_streamlit_command()
    try_start_streamlit()
    
    print("🏁 诊断完成！")
    print("请根据上面的信息排查问题，或将结果发给我帮你分析。")
